package com.doudou.oauth.request;

import com.doudou.oauth.entity.AppTokenUtil;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 傻男人
 * @Date: 2020/6/10 9:36
 * @Version: 1.0
 * @Description: 添加一些默认参数
 */
public class SimpleOAuth2RequestFactory extends DefaultOAuth2RequestFactory {
    public SimpleOAuth2RequestFactory(ClientDetailsService clientDetailsService) {
        super(clientDetailsService);
    }

    @Override
    public TokenRequest createTokenRequest(Map<String, String> requestParameters, ClientDetails authenticatedClient) {

        Map<String, String> processedParameters = processDefaultParameters(requestParameters);
        TokenRequest tokenRequest = super.createTokenRequest(processedParameters,authenticatedClient);
        return tokenRequest;
    }

    protected Map<String, String> processDefaultParameters(Map<String, String> requestParameters){
        if(requestParameters == null){
            requestParameters = new HashMap<>();
        }

        if(!requestParameters.containsKey(OAuth2Utils.GRANT_TYPE)){

            //默认grant_type=client_credentials 实现
            if(requestParameters.size()==2&&requestParameters.containsKey("client_id")&&requestParameters.containsKey("client_secret")){
                requestParameters.put(OAuth2Utils.GRANT_TYPE,"client_credentials");
            }else if(requestParameters.containsKey("redirect_uri")&&requestParameters.containsKey("code")){
                requestParameters.put(OAuth2Utils.GRANT_TYPE,"authorization_code");
            }
        }

        if(requestParameters.containsKey(AppTokenUtil.PERMANENT_CODE)){
            requestParameters.put(OAuth2Utils.GRANT_TYPE, AppTokenUtil.PERMANENT_CODE);
        }
        if(requestParameters.containsKey(AppTokenUtil.USER_ACCOUNT)){
            requestParameters.put(OAuth2Utils.GRANT_TYPE,AppTokenUtil.USER_ACCOUNT);
        }

        if(requestParameters.containsKey(AppTokenUtil.APP_CODE)){
            requestParameters.put(OAuth2Utils.GRANT_TYPE,AppTokenUtil.APP_CODE);
        }

        if(requestParameters.containsKey(AppTokenUtil.TENANT_ID) && requestParameters.containsKey(AppTokenUtil.SCHOOL_ID)){
            requestParameters.put(OAuth2Utils.GRANT_TYPE,AppTokenUtil.OPERATION_SERVICE);
            return requestParameters;
        }

        if(requestParameters.containsKey(AppTokenUtil.SCHOOL_ID)){
            requestParameters.put(OAuth2Utils.GRANT_TYPE,AppTokenUtil.SCHOOL_ID);
        }

        return requestParameters;
    }

}

